package cn.edu.gsau.info.util;

import cn.edu.gsau.info.exception.BusinessException;
import cn.edu.gsau.info.models.Code;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期格式化转换
 */
public class DateUtil {
    /**
     * @description: 字符串转日期
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static Date stringToDate(String dateString){
        return stringToDate(dateString,"yyyy-MM-dd");
    }

    /**
     * @description: 字符串转日期
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static Date stringToDate(String string,String pattern){
        DateFormat df = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = df.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
            new BusinessException(Code.BUSINESS_EXCEPTION,"时间格式异常");
        }
        return date;
    }

    /**
     * @description: 日期转字符串
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static String dateToString(Date date){
        return dateToString(date,"yyyy-MM-dd");
    }
    /**
     * @description: 日期转字符串
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static String dateToString(Date date, String pattern){
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(date);
    }


    /**
     * @description: 字符串转日期，带时间
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static Date stringToDatetime(String dateString){
        return stringToDatetime(dateString,"yyyy-MM-dd HH:mm:ss");
    }
    /**
     * @description: 字符串转日期，带时间
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static Date stringToDatetime(String string,String pattern){
        DateFormat df = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = df.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
            new BusinessException(Code.BUSINESS_EXCEPTION,"时间格式异常");
        }
        return date;
    }

    /**
     * @description: 日期转字符串，带时间
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static String datetimeToString(Date date){
        return datetimeToString(date,"yyyy-MM-dd HH:mm:ss");
    }
    /**
     * @description: 日期转字符串，带时间
     * @author: liu-maobing
     * @date:
     * @param:
     * @return:
     **/
    public static String  datetimeToString(Date date, String pattern){
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(date);
    }
}
